package com.ktjiaoyu.server.exception;

import com.ktjiaoyu.server.vo.RespBean;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 * @Author JieGe
 * @Create 2022/3/26 - 21:16
 * @Description
 */
@RestControllerAdvice
public class GlobalExceptionHandle {
    /**
     * 服务器报错统一返回信息
     */
    private static final String INTERNAL_SERVER_ERROR = "内部服务器错误";

    /**
     * 数据完整性约束异常(外键、主键或唯一键)
     */
    @ExceptionHandler(value =  {SQLIntegrityConstraintViolationException.class})
    public RespBean sQLIntegrityConstraintViolationExceptionHandler(
            SQLIntegrityConstraintViolationException e) {
        e.printStackTrace();
        return RespBean.error(e.getMessage());
    }

    /**
     * IO异常
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    public RespBean iOExceptionHandler(IOException ex) {
        ex.printStackTrace();
        return RespBean.error("IO异常： " + ex.getMessage());
    }

    /**
     * 405错误
     * @param ex
     * @return
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public RespBean request405(HttpRequestMethodNotSupportedException ex) {
        ex.printStackTrace();
        return RespBean.error("不支持请求方法: " + ex.getMessage());
    }


    /**
     * 超时异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SocketTimeoutException.class)
    public RespBean SocketTimeoutException(SocketTimeoutException ex) {
        ex.printStackTrace();
        return RespBean.error("连接超时,请检查网络环境或重试: " + ex.getMessage());
    }

    /**
     * 处理入参异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public RespBean handleIllegalParamException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        return RespBean.error("参数不合法" + e.getMessage());
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value =  {Exception.class})
    public RespBean exceptionHandle(Exception e) {
        RespBean responseData;
        if (e instanceof NoHandlerFoundException) {
            responseData = RespBean.error("接口地址不存在: "+ e.getMessage());
        } else {
            responseData = RespBean.error(e.getMessage());
        }
        e.printStackTrace();
        return responseData;
    }
}
